package cn.dugcrs.system.service.impl;

import cn.dugcrs.system.domain.Role;
import cn.dugcrs.system.mapper.RoleMapper;
import cn.dugcrs.system.service.IRoleService;
import cn.dugcrs.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gubcog
 * @since 2022-05-13
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void save(Role role) {
        // 新增并返回自增id
        roleMapper.save(role);
        // 通过返回的自增id添加相关联的数据表
        initRelationTable(role);

    }

    private void initRelationTable(Role role) {
        // 删除历史数据（冗余的垃圾数据）
        roleMapper.removeRoleMenuByRoleId(role.getId());
        roleMapper.removeRolePermissionByRoleId(role.getId());
        // 保存新的数据
        roleMapper.saveRoleMenu(role.getId(), role.getMenus());
        roleMapper.saveRolePermission(role.getId(), role.getPermissions());
    }


    @Override
    public void update(Role role) {
        super.update(role);
    }


    @Override
    public void remove(Long id) {
        roleMapper.removeRoleMenuByRoleId(id);
        roleMapper.removeRolePermissionByRoleId(id);
        roleMapper.remove(id);
    }
}
